package fun.hijklmn.magic.statistic.server.service.impl;

import fun.hijklmn.magic.common.utils.UUIDUtil;
import fun.hijklmn.magic.statistic.server.pojo.Resource;
import fun.hijklmn.magic.statistic.server.pojo.ResourceStatistic;
import fun.hijklmn.magic.statistic.server.service.StatisticService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.mongodb.core.query.UpdateDefinition;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @Description
 * @Author fs
 * @Date 2021/6/3 16:53
 * @Version 0.0.1-SNAPSHOT
 **/
@Slf4j
@Service
public class StatisticServiceImpl implements StatisticService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void statistic(ResourceStatistic resourceStatistic) {

        if ("count".equals(resourceStatistic.getType())) {

            synchronized (resourceStatistic.getUrl()) {

                Query query = new Query(Criteria.where("url").is(resourceStatistic.getUrl()));

                List<Resource> resourceList = mongoTemplate.find(query, Resource.class, resourceStatistic.getResType());

                if (CollectionUtils.isEmpty(resourceList)) {
                    Resource resource = new Resource();
                    resource.setId(UUIDUtil.uuid());
                    resource.setCount(1);
                    resource.setLike(0);
                    resource.setStatus(0);
                    resource.setType(resourceStatistic.getResType());
                    resource.setCreateTime(LocalDateTime.now());
                    resource.setUrl(resourceStatistic.getUrl());
                    mongoTemplate.insert(resource, resource.getType());
                } else {
                    Resource resource = resourceList.get(0);
                    Update update = new Update();
                    update.set("count", resource.getCount() + 1);
                    mongoTemplate.updateFirst(new Query(Criteria.where("_id").is(resource.getId())), update, resourceStatistic.getResType());
                }

            }

        }

    }

}
